package com.wonders.healthcitydoctor.ui.webview;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.wonders.healthcitydoctor.HtmlUrl;
import com.wonders.healthcitydoctor.R;
import com.wonders.healthcitydoctor.eventbus.StartBrotherEvent;
import com.wonders.healthcitydoctor.hx.ChatActivity;
import com.wonders.healthcitydoctor.hx.ConversationListActivity;
import com.wonders.healthcitydoctor.ui.base.BaseBackActivity;
import com.wonders.healthcitydoctor.ui.base.BaseMainActivity;
import com.wonders.healthcitydoctor.ui.map.QrCodeFragment;
import com.wonders.healthcitydoctor.util.LogUtil;
import com.wonders.healthcitydoctor.util.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static java.security.AccessController.getContext;

public class WebviewActivity extends BaseBackActivity implements View.OnClickListener {

    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.webView)
    BridgeWebView webView;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    private String url = "";
    private String title = "";
    private String type = "";
    private final int RC_HX_PERM=0x135;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page_item);
        ButterKnife.bind(this);
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        type = getIntent().getStringExtra("type");
//        initTile();
        webView.setDefaultHandler(new DefaultHandler());
        LogUtil.i("data===", title + "," + url + "," + type);

        initWebView();

        LogUtil.i("onCreateView===", "webviewFrageOnCreateView");
    }

//    @Override
//    public void onSupportVisible() {
//        super.onSupportVisible();
//
//    }

//    @Override
//    protected void onVisibleToUser() {
//        super.onVisibleToUser();
//        LogUtil.i("refrush",isCreatView+"");
//        if (!isCreatView) {
//            LogUtil.i("refrush",type);
//            switch (type) {
//                case "gotoWeb":
//                    webView.loadUrl(url);
//                    break;
//                case "addFamily":
//                    webView.loadUrl(url);
//                    break;
//            }
//        }
//        isCreatView=false;
//    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        String ua = webSettings.getUserAgentString();
        webSettings.setUserAgentString(ua + " android_appName");
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setDomStorageEnabled(true);// 开启 DOM storage API 功能
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置 缓存模式
        //开启 database storage API 功能
        webSettings.setDatabaseEnabled(false);
        //开启 Application Caches 功能
        webSettings.setAppCacheEnabled(false);
        String cookie = (String) SPUtils.get(getApplicationContext(), getString(R.string.cookie), "");
        syncCookie(getApplicationContext(), cookie);

//        registerJsbridge();
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                progressbar.setProgress(newProgress);
                if (newProgress == 100) {
//                    hideProgressDialog();
                    progressbar.setVisibility(View.GONE);
//                    registerJsbridge();
                }
            }
        });
        webView.setWebViewClient(new BridgeWebViewClient(webView) {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
        registerJsbridge();
        webView.loadUrl(url);
    }


    public void initTile() {
        View rl_title = null;
        if (type.equals("jkzxScreen")) {
            rl_title = LayoutInflater.from(getApplicationContext()).inflate(R.layout.include_main_top_edit, null);
        } else {
            rl_title = LayoutInflater.from(getApplicationContext()).inflate(R.layout.include_title, null);
        }
        llRoot.addView(rl_title, 0);
    }

    public void gotoWebView(String url, String title, String type) {

    }

    public void getCurrentJwd(String data, CallBackFunction function) {

    }

    // 设置cookie
    public void syncCookie(Context context, String cookies) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();//移除
        LogUtil.i("cookie", url + "," + cookies);
        cookieManager.setCookie(url, cookies);
        CookieSyncManager.getInstance().sync();
    }

    public void registerJsbridge() {
        //跳转页面
        webView.registerHandler("gotoWebView", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("gotoWebView", " " + data);
                JSONObject jsonData;
                try {
                    jsonData = new JSONObject(data);
                    url = jsonData.getString("url");
                    if (jsonData.has("title")) {
                        title = jsonData.getString("title");
                    } else {
                        title = "";
                    }
                    if (jsonData.has("type")) {
                        type = jsonData.getString("type");
                    } else {
                        type = "";
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                EventBus.getDefault().post(new StartBrotherEvent(WebviewFragment.newInstance(HtmlUrl.hostIp + url, title)));
                gotoWebView(HtmlUrl.hostIp + url, title, type);
            }

        });
        //家人列表需要返回
        webView.registerHandler("backtoWebView", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("backtoWebView", data + "");
            }
        });
        //跳转即时通讯
        webView.registerHandler("CommunicateOnLine", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("CommunicateOnLine", data + "");
            }
        });
        //获取经纬度
        webView.registerHandler("getJwd", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("getJwd",data+"");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("latitude", curLatitude + "");
                    jsonObject.put("longitude", curLongitude + "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                LogUtil.i("jsonobject", jsonObject.toString());
//                ToastMessageShort(jsonObject.toString());
                function.onCallBack(jsonObject.toString());
            }
        });
        //跳转地图
        webView.registerHandler("gotoMap", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("gotoMap", data + "");
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    double latitude = Double.parseDouble(jsonObject.getString("latitude"));
                    double longitude = Double.parseDouble(jsonObject.getString("longitude"));
                    String hosName = jsonObject.getString("hosName");
                    gotoMap(latitude, longitude, hosName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //收藏
        webView.registerHandler("loadScImg", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("loadScImg", data);
                String sfsc = "";
                try {
                    JSONObject object = new JSONObject(data);
                    sfsc = object.getString("sfsc");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                loadScImg(sfsc);
            }
        });
        //打电话
        webView.registerHandler("callPhone", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("callPhone", data);
                String phoneNumber = "";
                try {
                    JSONObject object = new JSONObject(data);
                    phoneNumber = object.getString("phoneNumber");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
                        + phoneNumber));
                startActivity(intent);
            }
        });
        webView.registerHandler("easemod", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("easemod", " " + data);
                JSONObject jsonData;
                try {
                    jsonData = new JSONObject(data);
                    String userName = jsonData.getString("userName");
                    Intent chat = new Intent(WebviewActivity.this, ChatActivity.class);
                    chat.putExtra(EaseConstant.EXTRA_USER_ID,userName);  //对方账号
                    startActivity(chat);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        });
        webView.registerHandler("getConversationList", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i("getConversationList", " " + data);
                conversationList();

            }

        });
//        webView.callHandler("jsLoadScImg", "", new CallBackFunction() {
//            @Override
//            public void onCallBack(String data) {
////                ToastMessageShort(data);
//            }
//        });
    }
    @AfterPermissionGranted(RC_HX_PERM)
    public void conversationList() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(getApplicationContext(), PERMISSIONS)) {
                // Have permission, do the thing!
                startActivity(new Intent(getApplicationContext(),ConversationListActivity.class));

            } else {
                // Ask for one permission
                EasyPermissions.requestPermissions(this, "需要读写存储的权限",
                        RC_HX_PERM, PERMISSIONS);
            }
        } else {
            startActivity(new Intent(getApplicationContext(),ConversationListActivity.class));
        }
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        super.onPermissionsDenied(requestCode, perms);
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        super.onPermissionsGranted(requestCode, perms);
        switch (requestCode){
            case RC_HX_PERM:
                startActivity(new Intent(getApplicationContext(),ConversationListActivity.class));
                break;
        }

    }
    public void setTitle(String title) {
        ImageView img_back = (ImageView) findViewById(R.id.image_back);
        TextView txt_title = (TextView) findViewById(R.id.tv_title);
        txt_title.setText(title + "");
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                    _mActivity.onBackPressed();
               finish();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        });
    }

    public void setTitle(String title, String rightText, int imgSrc) {
        ImageView img_back = (ImageView) findViewById(R.id.image_back);
        TextView txt_title = (TextView) findViewById(R.id.tv_title);
        TextView right_text = (TextView)findViewById(R.id.right_text);
        ImageView right_img = (ImageView) findViewById(R.id.right_img);
        txt_title.setText(title);
        if (!rightText.equals("")) {
            right_text.setText(rightText);
            right_text.setOnClickListener(this);
        }
        if (imgSrc != 0) {
            right_img.setImageResource(imgSrc);
            right_img.setOnClickListener(this);
        }
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                    _mActivity.onBackPressed();
                finish();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        });

    }

    public void setEditTitle( String hint, int leftSrc, int rightSrc) {
        ImageView img_left = (ImageView) findViewById(R.id.image_left);
        ImageView img_right = (ImageView) findViewById(R.id.image_right);
        TextView text_hint = (TextView) findViewById(R.id.text_hint);
        final EditText et_title = (EditText) findViewById(R.id.et_title);
        final LinearLayout mLayoutDefaultText = (LinearLayout) findViewById(R.id.layout_default);
        text_hint.setText(hint);
        if (leftSrc != 0) {
            img_left.setImageResource(leftSrc);
        }
        if (rightSrc != 0) {
            img_right.setImageResource(rightSrc);
        }
        img_left.setOnClickListener(this);
        img_right.setOnClickListener(this);
        et_title.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    setOnEditClickListener(v, et_title.getText().toString());
                }
                return false;
            }
        });

        // editText 离开监听
        et_title.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // hasFocus 为false时表示点击了别的控件，离开当前editText控件
                if (!hasFocus) {
                    if ("".equals(et_title.getText().toString())) {
                        mLayoutDefaultText.setVisibility(View.VISIBLE);
                    }
                } else {
                    mLayoutDefaultText.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_left:
                setOnLeftClickListener(v);
                break;
            case R.id.right_text:
                setOnRightClickListener(v);
                break;
            case R.id.image_right:
                setOnRightClickListener(v);
            case R.id.right_img:
                setOnRightClickListener(v);
                break;

        }
    }

    public void setOnLeftClickListener(View v) {


    }

    public void setOnRightClickListener(View v) {
    }

    public void setOnEditClickListener(View v, String editText) {
    }

    public void loadScImg(String sfsc) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }

            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.clearView();
            webView.removeAllViews();

            try {
                webView.destroy();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
//            InputCleanLeakUtils.fixInputMethodManagerLeak(getContext());
        }
    }


    public void gotoMap(double latitude, double longitude, String hosName) {
    }

//    @Override
//    public boolean onBackPressedSupport() {
////        switch (type) {
////            case "gotoWeb":
////                isCreatView=true;
////                break;
////            case "addFamily":
////                isCreatView=true;
////                break;
////        }
//        return super.onBackPressedSupport();
//
//    }
}
